package com.jingdianjichi.gateway.auth.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName:LoginFilter
 * Package:com.jingdianjichi.gateway.auth.filter
 * Description:
 *
 * @Author fst
 * @Create 2025/1/3 20:52
 * @Version 1.0
 */
@Component
public class LoginFilter implements GlobalFilter
{
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url=request.getURI().getPath();

        if(url.equals("auth/user/doLogin"))
        {
            return chain.filter(exchange);
        }

        SaTokenInfo saTokenInfo= StpUtil.getTokenInfo();

        String LoginId= (String) saTokenInfo.getLoginId();

        if(LoginId.equals(""))
        {
            throw new Exception("未获取用户信息");
        }
        mutate.header("loginId",LoginId);

        return chain.filter(exchange.mutate().request(mutate.build()).build());

    }
}
